#include <48func.h>
//int recvFile(int sockfd){
//    // 先收文件名
//    char filename[1024] = {0};
//    int length;
//    recv(sockfd,&length,sizeof(int),0);
//    recv(sockfd,filename,length,0);
//    int fd = open(filename,O_RDWR|O_CREAT,0666);
//    char buf[4096] = {0};
//    recv(sockfd,&length,sizeof(int),0);
//    ssize_t sret = recv(sockfd,buf,length,0);
//    write(fd,buf,sret);
//    return 0;
//}
int recvn(int sockfd, void *buf, int length){
    int total = 0;//记录已经收到的数据的长度
    char *p = (char *)buf;
    while(total < length){
        ssize_t sret = recv(sockfd,p+total,length-total,0);
        total += sret;
    }
    return total;
}
int recvFile(int sockfd){
    // 先收文件名
    char filename[1024] = {0};
    int length;
    //recv(sockfd,&length,sizeof(int),MSG_WAITALL);
    //recv(sockfd,filename,length,MSG_WAITALL);
    recvn(sockfd,&length,sizeof(length));
    recvn(sockfd,filename,length);
    off_t filesize;
    recvn(sockfd,&length,sizeof(length));
    recvn(sockfd,&filesize,length);
    printf("filesize = %ld\n", filesize);
    int fd = open(filename,O_RDWR|O_CREAT,0666);
    while(1){
        char buf[4096] = {0};
        //recv(sockfd,&length,sizeof(int),MSG_WAITALL);
        recvn(sockfd,&length,sizeof(length));
        if(length != 1000){
            printf("length = %d\n", length);
        }
        if(length == 0){
            break;
        }
        //ssize_t sret = recv(sockfd,buf,length,MSG_WAITALL);
        recvn(sockfd,buf,length);
        write(fd,buf,length);
    }
    close(fd);
    return 0;
}
int main(int argc, char *argv[])
{
    // ./client 192.168.118.128 1234
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_STREAM,0);//ipv4 tcp
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(atoi(argv[2]));
    serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
    int ret = connect(sockfd,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
    ERROR_CHECK(ret,-1,"connect");
    recvFile(sockfd);
    close(sockfd);
    return 0;
}

